package org.cleverframe.modules.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.cleverframe.common.controller.BaseController;
import org.cleverframe.common.persistence.tree.BuildTreeUtil;
import org.cleverframe.common.persistence.tree.ITreeNode;
import org.cleverframe.common.vo.AjaxMessage;
import org.cleverframe.modules.sys.SysBeanNames;
import org.cleverframe.modules.sys.SysJspUrlPath;
import org.cleverframe.modules.sys.entity.Menu;
import org.cleverframe.modules.sys.service.MenuService;
import org.cleverframe.webui.easyui.data.DataGridJson;
import org.cleverframe.webui.easyui.data.TreeGridNodeJson;
import org.cleverframe.webui.easyui.data.TreeNodeJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统菜单<br>
 * 
 * @author LiZhiWei
 * @version 2015年6月4日 下午9:39:32
 */
@Controller
@RequestMapping("/${mvcPath}/sys")
@Transactional(readOnly = true)
public class MenuController extends BaseController
{
	@Autowired
	@Qualifier(SysBeanNames.MenuService)
	private MenuService menuService;
	
    /**
     * 跳转到菜单管理页面<br>
     */
	@RequestMapping("/getSysMenuJsp")
	public ModelAndView getSysMenuJsp(HttpServletRequest request, HttpServletResponse response)
	{
		ModelAndView mav = new ModelAndView(SysJspUrlPath.SysMenu);
		return mav;
	}
	
	/**
	 * 获取所有菜单信息<br>
	 * @return 返回EasyUI TreeGrid控件格式数据
	 */
	@ResponseBody
	@RequestMapping("/getAllMenu")
	public DataGridJson<TreeGridNodeJson<Menu>> getAllMenu(HttpServletRequest request, HttpServletResponse response)
	{
		DataGridJson<TreeGridNodeJson<Menu>> treeGrid = new DataGridJson<TreeGridNodeJson<Menu>>();
		List<Menu> menuList = this.menuService.getAllMenu();
		for (Menu menu : menuList)
		{
			TreeGridNodeJson<Menu> node = new TreeGridNodeJson<Menu>(menu.getParentId(), menu);
			treeGrid.addRow(node);
		}
		return treeGrid;
	}
	
	/**
     * 查询菜单信息<br>
     * @return 返回EasyUI TreeGrid控件格式数据
	 */
	@ResponseBody
	@RequestMapping("/findMenu")
	public DataGridJson<TreeGridNodeJson<Menu>> findMenu(
			HttpServletRequest request, 
			HttpServletResponse response,
            @RequestParam(value = "category-search", required = false, defaultValue = "") String category,
            @RequestParam(value = "menuType-search", required = false, defaultValue = "") String menuType,
            @RequestParam(value = "name-search", required = false, defaultValue = "") String name,
            @RequestParam(value = "id-search", required = false, defaultValue = "-1") Long id,
            @RequestParam(value = "uuid-search", required = false, defaultValue = "") String uuid)
    {
        DataGridJson<TreeGridNodeJson<Menu>> treeGrid = new DataGridJson<TreeGridNodeJson<Menu>>();
        List<Menu> menuList = this.menuService.findMenu(category, menuType, name, id, uuid);
        for (Menu menu : menuList)
        {
            TreeGridNodeJson<Menu> node = new TreeGridNodeJson<Menu>(menu.getParentId(), menu);
            treeGrid.addRow(node);
        }
        return treeGrid;
    }
	
    /**
     * 获取所有菜单信息，排除当前菜单以及当前菜单的所有下级菜单<br>
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/getMenuTreeExcludeOneself")
    public List<ITreeNode> getMenuTreeExcludeOneself(
            HttpServletRequest request, 
            HttpServletResponse response, 
			@RequestParam(value = "fullPath", required = false, defaultValue = "XXX") String fullPath)
    {
        fullPath = fullPath + "%";
        List<Menu> menuList= menuService.getMenuTreeExcludeOneself(fullPath);
        List<ITreeNode> nodes = new ArrayList<ITreeNode>();
        for (Menu menu : menuList)
        {
            TreeNodeJson node = new TreeNodeJson(menu.getParentId(), menu.getId(), menu.getFullPath(), menu.getName(), menu.getIcon(), false, "open");
            nodes.add(node);
        }
        return BuildTreeUtil.bulidTree(nodes);
    }
	
    /**
     * 获取特定类别的菜单<br>
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/findMenuByCategory")
	public List<ITreeNode> findMenuByCategory(
	        HttpServletRequest request, 
	        HttpServletResponse response, 
	        @RequestParam(value = "category", required = true) String category)
	{
		List<Menu> menuList = menuService.findMenuByCategory(category);
		List<ITreeNode> nodes = new ArrayList<ITreeNode>();
		for (Menu menu : menuList)
		{
			TreeNodeJson node = new TreeNodeJson(menu.getParentId(), menu.getId(), menu.getFullPath(), menu.getName(), menu.getIcon(), false, "open");
			node.addAttributes("href", menu.getHref());
			nodes.add(node);
		}
		return BuildTreeUtil.bulidTree(nodes);
	}
    
	/**
	 * 新增菜单<br>
	 */
	@ResponseBody
	@RequestMapping("/addMenu")
	@Transactional(readOnly = false)
	public AjaxMessage addMenu(HttpServletRequest request, HttpServletResponse response, @Valid Menu menu, BindingResult bindingResult)
	{
		AjaxMessage message = new AjaxMessage();
		if (beanValidator(bindingResult, message))
		{
			if(menuService.addMenu(menu, message))
			{
			    message.setMessage("菜单数据保存成功");
			}
			else
			{
			    message.setSuccess(false);
			}
		}
		return message;
	}
	
	/**
	 * 更新菜单<br>
	 */
	@ResponseBody
	@RequestMapping("/updateMenu")
	@Transactional(readOnly = false)
	public AjaxMessage updateMenu(HttpServletRequest request, HttpServletResponse response, @Valid Menu menu, BindingResult bindingResult)
	{
        AjaxMessage message = new AjaxMessage();
        if (beanValidator(bindingResult, message))
        {
            if (menuService.updateMenu(menu, message))
            {
                message.setMessage("菜单数据更新成功");
            }
            else
            {
                message.setSuccess(false);
            }
        }
        return message;
	}
	
	/**
	 * 更新菜单<br>
	 */
	@ResponseBody
	@RequestMapping("/deleteMenu")
	@Transactional(readOnly = false)
	public AjaxMessage deleteMenu(HttpServletRequest request, HttpServletResponse response, @Valid Menu menu, BindingResult bindingResult)
	{
        AjaxMessage message = new AjaxMessage();
        if (beanValidator(bindingResult, message))
        {
            String fullPath = menu.getFullPath() + "%";
            int count = menuService.deleteMenu(fullPath);
            message.setMessage("菜单删除成功，删除菜单数：" + count);
        }
        return message;
	}
	
	/**
	 * 获取角色拥有的菜单<br>
	 * @param roleId 角色ID
	 * @return 
	 */
    @ResponseBody
    @RequestMapping("/findMenuByRoleId")
	public List<Menu> findMenuByRoleId(
	        HttpServletRequest request, 
	        HttpServletResponse response, 
	        @RequestParam(value = "roleId", required = true) Long roleId)
    {
        List<Menu> menuList = menuService.findMenuByRoleId(roleId);
        return menuList;
    }
    
    /**
     * 查询用户拥有的所有菜单<br>
     * @return 返回EasyUI Tree控件格式数据
     */
    @ResponseBody
    @RequestMapping("/findMenuByUserId")
    public List<Menu> findMenuByUserId(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "userId", required = true) Long userId)
    {
        List<Menu> menuList = menuService.findMenuByUserId(userId);
        return menuList;
    }
    
    /**
     * 获取当前用户拥有的菜单，根据菜单类别过滤<br>
     * @param category 菜单类别
     * @return 菜单集合
     */
    @ResponseBody
    @RequestMapping("/findMenuByCurrentUserAndCategory")
    public List<ITreeNode> findMenuByCurrentUserAndCategory(
            HttpServletRequest request, 
            HttpServletResponse response, 
            @RequestParam(value = "category", required = true) String category)
    {
        List<Menu> menuList = menuService.findMenuByUserIdAndCategory(userUtils.getCurrentUserId(), category);
        List<ITreeNode> nodes = new ArrayList<ITreeNode>();
        for (Menu menu : menuList)
        {
            TreeNodeJson node = new TreeNodeJson(menu.getParentId(), menu.getId(), menu.getFullPath(), menu.getName(), menu.getIcon(), false, "open");
            node.addAttributes("href", menu.getHref());
            nodes.add(node);
        }
        return BuildTreeUtil.bulidTree(nodes);
    }
}
